package com.sunbeam.utils;

import java.lang.reflect.InvocationTargetException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.converters.DateConverter;

/**
 * @Title: FromUtils.java
 * @Package com.sunbeam.utils
 * @Description: TODO
 * @author lyz lyzpoq_gmail_com
 * @date 2014/02/11 15:26:20
 * @version V1.0
 */
public class WebUtils {
	
	/**
	 * 
	 * @Title: form2Bean
	 * @Description: TODO
	 * @param @param request
	 * @param @param beanClass
	 * @param @return
	 * @return T
	 * @throws
	 */
	public static <T> T form2Bean(HttpServletRequest request,Class<T> beanClass){
		Enumeration<String> names= request.getParameterNames();
		T bean;
		try {
			 bean=beanClass.newInstance();
			while(names.hasMoreElements()){
				String name=names.nextElement();
				System.out.println(name+"----"+request.getParameter(name));
				BeanUtils.copyProperty(bean, name, request.getParameter(name));
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
		return bean;
	}
	
	/**
	 * 
	 * @Title: copyBeans
	 * @Description: TODO
	 * @param @param dest
	 * @param @param orig
	 * @return void
	 * @throws
	 */
	public static <T> T copyBeans(Class<T> destClass,Object orig){
		T dest=null;
		try {
			dest = destClass.newInstance();
		} catch (InstantiationException | IllegalAccessException e1) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e1);
		}

		DateConverter dateConverter = new DateConverter();
		dateConverter.setPattern("yyyy-MM-dd");
		ConvertUtils.register(dateConverter, java.util.Date.class);
		
		/*
		ConvertUtils.register(new Converter(){
			@Override
			public Object convert(Class type, Object value) {
				if(value==null){
					return null;
				}
				String str=(String)value;
				if(str.trim().equals("")){
					return null;
				}
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
				try{
					return sdf.parse(str);
				}catch(ParseException e){
					throw new RuntimeException(e);
				}
			}
		}, Date.class);
		*/
		
		try {
			BeanUtils.copyProperties(dest, orig);
		} catch (IllegalAccessException | InvocationTargetException e) {
			throw new RuntimeException(e);
		}
		return dest;
	}
	
	/**
	 * 
	 * @Title: generateID
	 * @Description: TODO
	 * @param @return
	 * @return String
	 * @throws
	 */
	public static String generateID(){
		return UUID.randomUUID().toString();
	}
}

